package activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.ci_edit.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import model.Constants;
import okhttp3.Call;
import adapter.MyViewPagerAdapter;

public class RegisterActivity extends AppCompatActivity {

    private ViewPager viewPager;//页卡内容
    private ImageView imageView;// 动画图片
    private TextView textView1,textView2;
    private List<View> views;// Tab页面列表
    private int offset = 0;// 动画图片偏移量
    private int currIndex = 0;// 当前页卡编号
    private Bitmap bmpW;// 动画图片宽度
    private View view1,view2;//各个页卡
    private EditText username,psw1,psw2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        InitImageView();
        Log.d("RegisterActivity","init image");
        InitTextView();
        Log.d("RegisterActivity","init text");
        InitViewPager();
        Log.d("RegisterActivity","init view pager");
    }
    /**
     *  初始化头标
     */

    private void InitTextView() {
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        textView1.setOnClickListener(new tvOnClickListener(0));
        textView2.setOnClickListener(new tvOnClickListener(1));
    }

    /**
     *
     * 头标点击监听 3 */
    private class tvOnClickListener implements OnClickListener{
        private int index=0;
        public tvOnClickListener(int i){
            index=i;
        }
        public void onClick(View v) {
            viewPager.setCurrentItem(index);
        }

    }
    /**
     2      * 初始化动画，这个就是页卡滑动时，下面的横线也滑动的效果，在这里需要计算一些数据
      */

    private void InitImageView() {
        imageView= (ImageView) findViewById(R.id.cursor);
        BitmapFactory.Options options = new BitmapFactory.Options();
        bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.cursor,options);// 获取图片宽度
        if(bmpW != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenW = dm.widthPixels;// 获取分辨率宽度
            offset = (screenW / 2 - bmpW.getWidth())/2;// 计算偏移量
            Matrix matrix = new Matrix();
            matrix.postTranslate(offset, 0);
            imageView.setImageMatrix(matrix);// 设置动画初始位置
        }else{
            Log.e("ERR","Failed to decode resource - ");
        }
    }
    private void InitViewPager() {
        viewPager=(ViewPager) findViewById(R.id.vPager);
        views=new ArrayList<View>();
        LayoutInflater inflater=getLayoutInflater();
        view1=inflater.inflate(R.layout.phone_register, null);
        view2=inflater.inflate(R.layout.email_register, null);
        views.add(view1);
        views.add(view2);
        viewPager.setAdapter(new MyViewPagerAdapter(views));
        viewPager.setCurrentItem(0);
        viewPager.addOnPageChangeListener(new MyOnPageChangeListener());
    }

    public class MyOnPageChangeListener implements OnPageChangeListener{

        int one = offset * 2 + bmpW.getWidth();// 页卡1 -> 页卡2 偏移量
        public void onPageScrollStateChanged(int arg0) {
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        public void onPageSelected(int arg0) {
            Animation animation = new TranslateAnimation(one*currIndex, one*arg0, 0, 0);
            currIndex = arg0;
            animation.setFillAfter(true);// True:图片停在动画结束位置
            animation.setDuration(300);
            imageView.startAnimation(animation);
            if(0 == arg0){
                username = (EditText)view1.findViewById(R.id.phone_username);
                psw1 = (EditText)view1.findViewById(R.id.phone_psw);
                psw2 = (EditText)view1.findViewById(R.id.phone_psw2);
                view1.findViewById(R.id.submitBtn_phone).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    final String name = username.getText().toString().trim();
                    final String pass1 = psw1.getText().toString();
                    final String pass2 = psw2.getText().toString();
                    Log.d("name",name);
                    if(name.length()<=0 || null == name){
                        Toast.makeText(RegisterActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                    }else {
                        register(name, pass1, pass2);
                    }
                }
                });
            }else{
                username = (EditText)view2.findViewById(R.id.email_username);
                psw1 = (EditText)view2.findViewById(R.id.email_psw);
                psw2 = (EditText)view2.findViewById(R.id.email_psw2);
                view2.findViewById(R.id.submitBtn_email).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        final String name = username.getText().toString();
                        final String pass1 = psw1.getText().toString();
                        final String pass2 = psw2.getText().toString();
                        if(name.length()<=0 || null == name){
                            Toast.makeText(RegisterActivity.this, "邮箱不能为空", Toast.LENGTH_SHORT).show();
                        }else {
                            register(name, pass1, pass2);
                        }
                    }
                });
            }
        }
    }

    private void register(final String name,final String pass1,final String pass2){
        if(pass1 == null || pass1.length() <= 0 || pass2 == null || pass2.length() <= 0){
            Toast.makeText(RegisterActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
        }else if(!pass1.equals(pass2)){
            Toast.makeText(RegisterActivity.this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
        }else {
            OkHttpUtils.post().url(Constants.SERVER_URL + "register")
                    .addParams("username", name)
                    .addParams("password", pass1)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            if (response.equals("IS_REGISTERD")) {
                                Toast.makeText(RegisterActivity.this, "该账号已被注册", Toast.LENGTH_SHORT).show();
                            } else if (response.equals("REGI_ERR")) {
                                Toast.makeText(RegisterActivity.this, "注册失败，请稍后再试", Toast.LENGTH_SHORT).show();
                            } else if (response.equals("REGI_SUCCESS")) {
                                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    });
        }
    }
}
